﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ErrorGeneratorServer
{
    class Program
    {
        static void Main(string[] args)
        {
            //Task.Factory.StartNew(() =>
            //{

            HttpListener listener = new HttpListener();
            listener.Prefixes.Add("http://localhost:6880/");
            while (true)
            {
                listener.Start();
                var context = listener.GetContextAsync().Result;

                var request = context.Request;
                var response = context.Response;
                //request.RawUrl.Split('?')

                Console.WriteLine($"Request From {request.UserHostAddress}");
                Console.WriteLine(request.RawUrl);
                var rawUrl = request.RawUrl;

                var dictionary = new Dictionary<string, string>();
                int successPercent = 10;
                //try
                //{
                //    dictionary = rawUrl
                //                .Split('/')[1]
                //                .Split('&')
                //                .ToDictionary(kvp => kvp.Split('?')[0].ToUpper(), kvp => kvp.Split('?')[1].ToUpper());
                //    successPercent = int.Parse(dictionary["sp".ToUpper()]);
                //}
                //catch (Exception)
                //{
                //    response.StatusCode = (int)HttpStatusCode.BadRequest;
                //    //throw;
                //}



                var bytes = Encoding.UTF8.GetBytes("Hello world");


                var random = new Random().Next(0, 100);
                Console.WriteLine(random);
                if (rawUrl.ToUpper() == "/favicon.ico".ToUpper())
                {
                    //successPercent = 100;
                }
                if (random <= 85)
                {
                    bytes = Encoding.UTF8.GetBytes("Error!");
                    response.StatusCode = (int)HttpStatusCode.InternalServerError;
                }
                response.ContentLength64 = bytes.Length;
                response.OutputStream.Write(bytes, 0, bytes.Length);
                response.OutputStream.Close();
                listener.Stop();
            }


            //});
        }
        public static void StartTestListener(int port)
        {
            var listener = new HttpListener();
            var ghe = Dns.GetHostEntry(Dns.GetHostName());
            foreach (var item in ghe.AddressList)
            {
                if (item.AddressFamily == AddressFamily.InterNetwork)
                {
                    listener.Prefixes.Add(String.Format("http://{1}:{0}/", port, item.ToString()));
                }
            }
            listener.Prefixes.Add(String.Format("http://localhost:{0}/", port));

            while (1 == 1)
            {
                listener.Start();
                listener.BeginGetContext((a) =>
                {
                    HttpListener hl = (HttpListener)a.AsyncState;
                    var ctx = hl.EndGetContext(a);
                    var req = ctx.Request;
                    var res = ctx.Response;
                    string responseString = "<HTML><BODY> Hello world!</BODY></HTML>";
                    var buff = System.Text.Encoding.UTF8.GetBytes(responseString);
                    res.ContentLength64 = buff.Length;
                    //res.StatusCode = (int)HttpStatusCode.InternalServerError;
                    var output = res.OutputStream;
                    output.Write(buff, 0, buff.Length);
                    output.Close();

                }, listener);
                var context = listener.GetContext();
                var request = context.Request;
                var response = context.Response;
                var outStream = response.OutputStream;
            }

        }

    }

}
